package com.itheima.reggie.common;

/**
 * @Author: cl
 * @Date: 2022/4/2 - 04 - 02
 * @Description:
 */

import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.RestController;

import java.sql.SQLException;
import java.sql.SQLIntegrityConstraintViolationException;


/**
 * 全局异常处理
 *
 * @RestControllerAdvice = @ControllerAdvice()+@ResponseBody
 */
@ControllerAdvice(annotations = {RestController.class, Controller.class})
@ResponseBody
@Slf4j
public class GlobalExceptionHandler_全局异常拦截处理 {
    /**
     * 异常处理方法
     *
     * @return
     */
    @ExceptionHandler(SQLIntegrityConstraintViolationException.class)
    public R<String> exceptionHandler(SQLIntegrityConstraintViolationException ex) {
        log.info(ex.getMessage());

        if(ex.getMessage().contains("Duplicate entry")){
            String[] split = ex.getMessage().split(" ");
            String msg = split[2] + "已存在";
            return R.error(msg);
        }
        return R.error("未知错误！");
    }
    @ExceptionHandler(SQLException.class)
    public R<String> exceptionHandler(SQLException ex) {
        log.info(ex.getMessage());

        return R.error("id不能自增！");
    }


    /**
     * 直接拦截RuntimeException异常
     */

//    @ExceptionHandler(RuntimeException.class)
//    public R<String> exceptionHandler(RuntimeException ex) {
//        log.info(ex.getMessage());
//
//        return R.error("当前分类下关联了套餐或者关联了菜品，不能删除！");
//    }


    /**
     * 异常处理方法
     * @return
     */
    @ExceptionHandler(CustomException_自定义异常.class)
    public R<String> exceptionHandler(CustomException_自定义异常 ex){
        log.error(ex.getMessage());
        return R.error(ex.getMessage());
    }
}
